// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package org.jetbrains.kotlin.idea.quickfix

import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.intentions.declarations.ConvertMemberToExtensionIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.psiUtil.containingClass

object DeclarationCantBeInlinedFactory : KotlinIntentionActionsFactory() {
    override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
        val function = diagnostic.psiElement as? KtNamedFunction ?: return emptyList()
        val containingClass = function.containingClass() ?: return emptyList()
        val fixes = mutableListOf<IntentionAction>()
        if (containingClass.isInterface()) {
            fixes.add(ConvertMemberToExtensionFix(function))
        } else if (function.hasModifier(KtTokens.OPEN_KEYWORD)) {
            fixes.add(RemoveModifierFix(function, KtTokens.OPEN_KEYWORD, false).asIntention())
        }
        return fixes
    }
}

private class ConvertMemberToExtensionFix(element: KtNamedFunction) : KotlinQuickFixAction<KtNamedFunction>(element) {
    override fun getText() = KotlinBundle.message("convert.member.to.extension")

    override fun getFamilyName() = text

    override fun startInWriteAction(): Boolean = false

    override fun invoke(project: Project, editor: Editor?, file: KtFile) {
        element?.also { ConvertMemberToExtensionIntention.Holder.convert(it) }
    }
}
